package com.lottery.api.exception;

import com.alibaba.druid.util.StringUtils;
import com.lottery.api.exception.MemberException;
import com.lottery.common.*;
import com.lottery.common.contants.Constants;
import com.lottery.common.contants.ReQueryResult;
import com.lottery.common.utils.MyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.BindException;
import java.util.List;

import static com.lottery.common.contants.ReQueryResult.TYPE_ONE_HUNDRED_ONE_STR;


/**
 * @author furutaka
 */
@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @Resource
    private StringRedisTemplate template;

    /**
     * 全局异常拦截
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = {Exception.class,NoHandlerFoundException.class})
    public ReQueryResult exceptionHandler(HttpServletRequest request, Exception e) {
        ReQueryResult result = new ReQueryResult();
        log.error("异常日志记录 {}",e.getMessage());
        log.info(ExceptionUtils.getFullStackTrace(e));
        if (e instanceof MemberException) {
            MemberException memberException = (MemberException) e;
            result.loginError("账号未登录");
            return result;
        }
        if (e instanceof MyException) {
            MyException myException = (MyException) e;
            result.error(Constants.PARAMS_ILLEGAL);
            return result;
        }
        if (e instanceof NoHandlerFoundException) {
            String ip = request.getHeader("X-FORWARDED-FOR");
            if (StringUtils.isEmpty(ip)) {
                ip = request.getRemoteAddr();
            }
            log.info("无url 访问ip : {}",ip);
            result.setResultCode(TYPE_ONE_HUNDRED_ONE_STR);
            result.setResultDesc("未找到url");
            return result;
        }
        result.error("系统异常");
        return result;
    }
}


